package com.example.ccj.b.c.custom.image;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;


import com.example.ccj.R;
import com.example.ccj.b.c.custom.adapter.AdapterForBigPhotoViewPager;
import com.example.ccj.b.c.custom.adapter.AdpterShowImages;
import com.example.ccj.b.c.recycler.Decoration;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.ToastUtils;
import com.example.ccj.u.media.DonloadImagesAndMp4Util;

import java.util.ArrayList;
import java.util.List;

/**
 * 图片大图展示
 * 2022年9月16日17:05:33
 */
public class ShowBigPictureControl extends RelativeLayout {

    public static final int SHOW_MODEL_ONLY_SHOW = 0;           //显示模式 仅做显示用 网络图片可以下载
    public static final int SHOW_MODEL_SELECT = 1;              //选择传入的图片 网络图片可以下载
    public static final int SHOW_MODEL_SHOW_AND_DELETE = 2;     //显示和删除传入的图片 网络图片可以下载


    private int showMode = SHOW_MODEL_ONLY_SHOW;
    private RecyclerView mRv1;
    private ViewPager viewPager;
    private ImageView dowload;
    private CheckBox selected;
    private boolean isCanDelete;
    private List<MLocalMedia> allImages;
    private List<MLocalMedia> deleteImages;
    private ShowBigImageChangeListener imageChangeListenear;
    private int backPosition = 0;//上一个
    private List<MLocalMedia> selectImages;//选中的
    MLocalMedia nowSelectImage = null;//当前显示的
    private TextView errorText;

    public ShowBigPictureControl(@NonNull Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ShowBigPictureControl(Context context){
        super(context);
        init();
    }

    private void init(){
        LayoutInflater.from(getContext()).inflate(R.layout.custom_adapter_recyler_image_horizontal, this);
        mRv1 = findViewById(R.id.my_add_image_recycler_images);
        dowload = findViewById(R.id.dowload_images);
        selected = findViewById(R.id.my_add_image_selected);
        viewPager = findViewById(R.id.view_pager);
        errorText = findViewById(R.id.view_error_text);
        dowload.setVisibility(View.GONE);
        deleteImages = new ArrayList<>();
        selectImages = new ArrayList<>();
    }

    //设置显示模式
    public ShowBigPictureControl setMode(int showMode){
        this.showMode = showMode;
        if (showMode == SHOW_MODEL_ONLY_SHOW) {
            selected.setVisibility(GONE);
            isCanDelete = false;
        } else if (showMode == SHOW_MODEL_SELECT) {
            isCanDelete = false;
        } else if (showMode == SHOW_MODEL_SHOW_AND_DELETE) {
            isCanDelete = true;
        } else {
            this.showMode = SHOW_MODEL_ONLY_SHOW;
            isCanDelete = false;
        }
        return this;
    }

    //设置数据
    public ShowBigPictureControl setData(List<MLocalMedia> images){
        allImages = images;
        return this;
    }

    //展示
    public void show() {
        initData();
        if (allImages != null && !allImages.isEmpty()) {
            errorText.setVisibility(GONE);
            if (nowPosition>=allImages.size()){
                nowPosition = allImages.size()-1;
            }
            allImages.get(nowPosition).nowShow = true;
            nowSelectImage = allImages.get(nowPosition);
            setViewPageData();
            setAdapterData();

            mRv1.smoothScrollToPosition(nowPosition);
            viewPager.setCurrentItem(nowPosition);
            if (nowSelectImage.imageType == 1) dowload.setVisibility(View.VISIBLE);
        }
    }

    private void setViewPageData(){
        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                //发生改变，如果当前不为空，将当前显示置为falese
                if (nowSelectImage != null) nowSelectImage.nowShow = false;
                //刷新上一张图片，就是刚才的当前
                mRv1.getAdapter().notifyItemChanged(backPosition);
                //上一张图片id置为当前
                backPosition = position;
                //当前选中图片置为当前移动到的图片
                nowSelectImage = allImages.get(position);
                //当前是否选中置为选中
                nowSelectImage.nowShow = true;
                //移动到选中位置
                mRv1.smoothScrollToPosition(position);
                //刷新
                mRv1.getAdapter().notifyItemChanged(position);
                //设置是否选中按钮的显示效果
                selected.setChecked(nowSelectImage.selected);
                if (nowSelectImage.imageType == MLocalMedia.IMAGE_TYPE_NETWORK) dowload.setVisibility(View.VISIBLE);
                else dowload.setVisibility(View.GONE);
            }
        });

        viewPager.setAdapter(new AdapterForBigPhotoViewPager(getContext(), allImages, new ShowAndHidePictureListener() {
            @Override
            public void onCallBack(boolean isShow) {
                LogUtils.d("当前要显示：" + isShow);
                if (isShow) {
                    //显示底部图片列表
                    showAnimation();
                } else {
                    //隐藏底部图片列表
                    hideAnimation();
                }
            }
        }));
    }

    private void initData(){
        selected.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    allImages.get(backPosition).selected = true;
                    selectImages.add(allImages.get(backPosition));
                } else {
                    allImages.get(backPosition).selected = false;
                    selectImages.remove(nowSelectImage);
                }
            }
        });
        //下载图片
        dowload.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (nowSelectImage.imageType == 1) {
                    DonloadImagesAndMp4Util donloadImages = new DonloadImagesAndMp4Util(getContext());
                    donloadImages.execute(nowSelectImage.urlPath);
                } else {
                    ToastUtils.showShort( "本地图片，无需下载");
                }
            }
        });
    }


    public void setecoration(){
        mRv1.addItemDecoration(new Decoration(getContext(),1));//处理分割线，图片上画删除按钮
    }

    /**
     * 默认Adapter赋值
     */
    private void setAdapterData(){
        //设置布局方式
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());//布局样式及点击事件
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);//水平方向显示
        mRv1.setLayoutManager(linearLayoutManager);
        mRv1.setAdapter(null);
        if (allImages != null && !allImages.isEmpty()) {
            AdpterShowImages imagesAdapter = new AdpterShowImages(getContext(), allImages, isCanDelete,new AdpterShowImages.OnItemClickListener() {
                @Override
                public void onItemsClick(int po) {//图片点击事件
                    viewPager.setCurrentItem(po);
                    nowSelectImage = allImages.get(po);
                }
            }, new AdpterShowImages.OnItemDeleteListener() {
                @Override
                public void onDelete(List<MLocalMedia> images, MLocalMedia deleteImage,int position) {
                    deleteImages.add(deleteImage);
                    selectImages.remove(deleteImage);
                    if (imageChangeListenear != null) {
                        imageChangeListenear.imageDelete(deleteImage,position);
                    }
                    viewPager.setCurrentItem(position);
                }
            });

            mRv1.setAdapter(imagesAdapter);
        }else{
            mRv1.setAdapter(null);
        }
    }

    int nowPosition= 0;

    public ShowBigPictureControl setShowPosition(int position) {
        nowPosition = position;
        return this;
    }

    public List<MLocalMedia> getAllImages(){
        return allImages;
    }
    public List<MLocalMedia> getDeleteImages(){
        return deleteImages;
    }
    public List<MLocalMedia> getSelectedImage(){
        return selectImages;
    }

    /**
     * 设置分割线样式
     * @param decoration Decoration
     */
    public void setNewDecoration(RecyclerView.ItemDecoration decoration){
        mRv1.addItemDecoration(decoration);
    }

    /**
     * 设置图片发生改变时的事件（删除、增加）
     * @param imageChangeListenear
     * @return
     */
    public ShowBigPictureControl setImageChangeListenear(ShowBigImageChangeListener imageChangeListenear){
        this.imageChangeListenear = imageChangeListenear;
        return this;
    }


    /**
     * 显示底部图片列表
     */
    private void showAnimation() {
        mRv1.setVisibility(View.VISIBLE);
        // 初始位置在屏幕下方，所以 translateY 设置为自身高度
        ObjectAnimator translationY = ObjectAnimator.ofFloat(mRv1, "translationY", mRv1.getHeight(), 0);
        translationY.setDuration(300);
        translationY.setInterpolator(new LinearInterpolator());

        ObjectAnimator alpha = ObjectAnimator.ofFloat(mRv1, "alpha", 0f, 1f);
        alpha.setDuration(300);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(translationY, alpha);
        animatorSet.start();


    }

    /**
     * 隐藏底部图片列表
     */
    private void hideAnimation() {
        // 最终位置在屏幕下方，所以 translateY 设置为自身高度
        //Y坐标平移控件高度的距离
        ObjectAnimator translationY = ObjectAnimator.ofFloat(mRv1, "translationY", 0, mRv1.getHeight());
        translationY.setDuration(300);
        translationY.setInterpolator(new LinearInterpolator());

        //透明
        ObjectAnimator alpha = ObjectAnimator.ofFloat(mRv1, "alpha", 1f, 0f);
        alpha.setDuration(300);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(translationY, alpha);
        animatorSet.start();

        animatorSet.addListener(new android.animation.Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(android.animation.Animator animation) {
            }

            @Override
            public void onAnimationEnd(android.animation.Animator animation) {
                mRv1.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationCancel(android.animation.Animator animation) {
            }

            @Override
            public void onAnimationRepeat(android.animation.Animator animation) {
            }
        });
    }









    public interface ShowAndHidePictureListener{
        void onCallBack(boolean isShow);
    }

}
